const tags = {
  state: {
    tagList: [
      { code: 'main', name: '首页' }
    ],
    activeIndex: 0
  },
  mutations: {
    // 初始化
    INIT_TAG (state, list) {
      state.tagList = list
    },
    // 切换
    SWITCH_TAG (state, code) {
      state.activeIndex = findIndex(state.tagList, code)
    },
    // 新增
    ADD_TAG (state, tag) {
      state.tagList.push(tag)
    },
    // 关闭指定页面
    CLOSE_TAG (state, code) {
      state.tagList.splice(findIndex(state.tagList, code), 1)
    },
    // 关闭全部
    CLOSE_ALL (state) {
      state.tagList = [{ code: 'main', name: '首页' }]
      state.activeIndex = 0
    }
  },
  actions: {
    initTag ({ commit }, list) {
      commit('INIT_TAG', list)
    },
    switchTag ({ commit }, tag) {
      commit('SWITCH_TAG', tag.code)
    },
    addTag ({ commit, state }, tag) {
      if (findIndex(state.tagList, tag.code) === -1) {
        commit('ADD_TAG', tag)
      }
      commit('SWITCH_TAG', tag.code)
    },
    closeTag ({ commit, state }, tag) {
      // 设置首页不可关闭
      if (tag.code === 'main') {
        return
      }
      let delIndex = findIndex(state.tagList, tag.code)
      if (delIndex < state.activeIndex) {
        --state.activeIndex
      }
      if (delIndex === state.activeIndex) {
        state.activeIndex = state.tagList.length - 2
      }
      commit('CLOSE_TAG', tag.code)
    },
    closeAllTag ({ commit }) {
      commit('CLOSE_ALL')
    },
    closeOtherTag ({ commit }, tag) {
      commit('CLOSE_ALL')
      if (tag.code !== 'HOME') {
        commit('ADD_TAG', tag)
        commit('SWITCH_TAG', tag.code)
      }
    }
  },
  getters: {
    tagList (state) {
      return state.tagList
    },
    activeIndex (state) {
      return state.activeIndex
    }
  }
}

function findIndex (array, code) {
  for (let index in array) {
    if (array[index].code === code) {
      return index
    }
  }
  return -1
}

export default tags

// 操作 切换 新增 关闭指定 关闭其他 关闭所有
